<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-row class="sensitive-content">
				<span>
					<el-button
						type="primary"
						size="small"
						@click="handleUploadShow"
					>
						{{ $t('dxn.game_rule.upload') }}
					</el-button>
				</span>

				<span>
					<el-button
						type="primary"
						size="small"
						:loading="downloadLoading"
						:disabled="downloadLoading"
						@click="handleDownload"
					>
						{{ $t('dxn.game_rule.download') }}
					</el-button>
				</span>

				<span class="show-tips">
					上传/下载仅支持excel文件
				</span>
			</el-row>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="dataList"
				style="width: 50%;margin-left: 10px;"
				:max-height="tableHeight"
				highlight-current-row
				header-align="center"
				:header-cell-style="getRowClass"
			>
				<el-table-column
					align="center"
					label="最后上传人"
					min-width="200"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					label="最后上传时间"
					min-width="200"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdAt || '-' }}
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-if="totalPage > 1"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:current-page.sync="pageNum"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			/>
		</template>
		<el-dialog
			:visible="uploadVisible"
			:destroy-on-close="true"
			:before-close="handleUploadClose"
			@close="handleUploadClose"
			center
			width="600px"
		>
			<div slot="title" class="header-title">
				<div class="title">
					上传敏感词文件
				</div>
			</div>
			<div style="text-align: center;">
				<div style="color:#3232ff;">
					{{ lastUploadFile ? lastUploadFile + '.xls' : '' }}
				</div>
				<div style="margin-top: 10px;">
					<el-upload
						v-if="!fileList.length"
						ref="upload"
						action=""
						accept=".xls,.xlsx"
						:file-list="fileList"
						:show-file-list="false"
						:auto-upload="false"
						:on-change="handleUploadFile"
					>
						<el-button size="small">
							点击上传本地文件
						</el-button>
						<div
							slot="tip"
							style="margin-top: 10px;color: #6d000e;"
						>
							{{
								lastUploadFile
									? '上传文件将覆盖当前文件'
									: '仅支持excel文件'
							}}
						</div>
					</el-upload>
					<div v-else>
						<div style="min-height: 40px;color: #3232ff;">
							{{ fileList[0].name }}
						</div>

						<template v-if="uploadStatus === 1">
							<div style="min-height: 40px;"></div>
							<span>上传中...</span>
						</template>

						<template v-else-if="uploadStatus === 2">
							<div style="min-height: 40px;">上传成功</div>
							<el-button size="small" @click="handleUploadFinish">
								确定
							</el-button>
						</template>

						<template v-if="isShowUploadBtn">
							<div style="min-height: 40px;">
								{{
									uploadStatus === 3
										? '上传失败，请重新上传'
										: ''
								}}
							</div>
							<el-button
								size="small"
								@click="handleUploadConfirm"
							>
								上传
							</el-button>
						</template>
					</div>
				</div>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'
export default {
	name: routerNames.sensitiveManager,
	components: {
		MainContent
	},
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			loading: false,
			downloadLoading: false,
			uploadVisible: false,
			lastUploadFile: '',
			uploadStatus: 0,
			fileList: [],
			dataList: [],
			totalPage: 0
		}
	},
	computed: {
		isShowUploadBtn() {
			return [0, 3].includes(this.uploadStatus)
		}
	},
	methods: {
		loadData() {
			this.loading = true
			this.dataList = []
			this.totalPage = 0
			const params = this.getParams()
			this.$api
				.getSensitiveRecordBend(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						this.dataList = res?.data?.record || []
						this.total = res?.data?.totalRecord
						this.totalPage = res?.data?.totalPage
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		handleUploadShow() {
			this.lastUploadFile = this.dataList[0]?.fileName || ''
			this.uploadVisible = true
		},
		handleUploadFile(file) {
			// 文件类型校验
			const fileSuffixArr = file.name?.split('.')
			const isAcceptSuffix = ['xls', 'xlsx'].includes(fileSuffixArr[1])
			if (!isAcceptSuffix) {
				return this.$message.success('仅支持excel文件')
			}
			this.lastUploadFile = ''
			this.fileList = [file]
		},
		handleUploadConfirm() {
			this.uploadStatus = 1 // 上传中
			const formData = new FormData()
			formData.append('file', this.fileList[0]?.raw)
			this.$api
				.uploadSensitiveBend(formData)
				.then(() => {
					this.uploadStatus = 2 // 上传成功
				})
				.catch(() => {
					this.uploadStatus = 3 // 上传失败
				})
		},
		handleUploadClose() {
			this.uploadVisible = false
			this.lastUploadFile = ''
			this.fileList = []
			this.uploadStatus = 0
		},
		handleUploadFinish() {
			this.handleUploadClose()
			this.loadData()
		},
		handleDownload() {
			// if (!this.dataList.length) {
			// 	this.$message.closeAll()
			// 	return this.$message.warning('没有上传记录，无法下载')
			// }
			this.downloadLoading = true
			this.$api
				.downloadSensitiveBend({})
				.then((res) => {
					if (res && res?.status === 200) {
						const result = res.data
						const disposition = res.headers['content-disposition']
						const fileNames = disposition && disposition.split("''")
						let fileName =
							Array.isArray(fileNames) &&
							fileNames.length &&
							fileNames[1]
						fileName = decodeURIComponent(fileName)
						const blob = new Blob([result], {
							type: 'application/octet-stream'
						})
						if ('download' in document.createElement('a')) {
							const downloadLink = document.createElement('a')
							downloadLink.download = fileName || ''
							downloadLink.style.display = 'none'
							downloadLink.href = URL.createObjectURL(blob)
							document.body.appendChild(downloadLink)
							downloadLink.click()
							URL.revokeObjectURL(downloadLink.href)
							document.body.removeChild(downloadLink)
						} else {
							window.navigator.msSaveBlob(blob, fileName)
						}
						this.$message({
							type: 'success',
							message: this.$t('common.download_success'),
							duration: 1500
						})
					} else {
						this.$message.error(this.$t('common.download_fail'))
					}
					this.downloadLoading = false
				})
				.catch(() => {
					this.downloadLoading = false
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.sensitive-content {
	margin-left: 10px;
	margin-bottom: 5px;
	span {
		margin-right: 20px;
	}
	.show-tips {
		color: #909399;
		font-size: 14px;
	}
}

::v-deep .el-dialog__header {
	padding: 0;
	color: #606266;
	border-bottom: 1px solid #ccc;
	.header-title {
		.title {
			line-height: 60px;
			font-weight: 700;
			color: #606266;
		}
	}
}
</style>
